const mongoose = require('mongoose');

const submissionSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: false // 支持匿名用户
  },
  exerciseId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Exercise',
    required: [true, '题目ID不能为空']
  },
  content: {
    type: String,
    required: [true, '写作内容不能为空'],
    trim: true,
    minlength: [50, '写作内容不能少于50个字符'],
    maxlength: [5000, '写作内容不能超过5000个字符']
  },
  wordCount: {
    type: Number,
    required: [true, '字数统计不能为空'],
    min: [50, '字数不能少于50字']
  },
  scores: {
    taskAchievement: {
      type: Number,
      min: 0,
      max: 9
    },
    coherence: {
      type: Number,
      min: 0,
      max: 9
    },
    vocabulary: {
      type: Number,
      min: 0,
      max: 9
    },
    grammar: {
      type: Number,
      min: 0,
      max: 9
    },
    overall: {
      type: Number,
      min: 0,
      max: 9
    }
  },
  feedback: {
    type: String,
    trim: true
  },
  strengths: [{
    type: String,
    trim: true
  }],
  improvements: [{
    type: String,
    trim: true
  }],
  aiResponseTime: {
    type: Number, // AI响应时间(毫秒)
    min: 0
  },
  status: {
    type: String,
    enum: ['pending', 'completed', 'failed'],
    default: 'pending'
  }
}, {
  timestamps: true
});

// 创建索引
submissionSchema.index({ userId: 1, createdAt: -1 });
submissionSchema.index({ exerciseId: 1 });
submissionSchema.index({ createdAt: -1 });

module.exports = mongoose.model('Submission', submissionSchema);
